<template>
  <div class="bedcard-dropdown">
    <div
      class="bedcard"
      :class="{ 'is-empty': !hasPatient }"
      @click="item.admissionId ? onPatientClick() : onAssignClick()"
      v-menus:right="menus"
      :key="renderKey"
    >
      <!-- 顶部区域：性别图标、姓名、年龄、床号 -->
      <div class="bedcard__header">
        <div class="left">
          <i class="iconfont" :class="genderClass"></i>
          <span class="name">{{ displayName || '空床' }}</span>
          <span v-if="age" class="age">{{ age }}岁</span>
          <span v-if="item.settlementType"
            ><dict-tag :options="sys_settlement_type" :value="item.settlementType"
          /></span>
        </div>
        <div class="right">
          <span class="bedno">{{ item.bedNo }}</span>
        </div>
      </div>

      <!-- 中部信息：诊断、主治医生、责任护士、住院时间 -->
      <div class="bedcard__body">
        <div class="flex">
          <div class="row flex-item">诊断：{{ hasPatient ? item.admissionDiagnosis : '' }}</div>
        </div>
        <div class="flex">
          <div class="row flex-item">医生：{{ hasPatient ? item.residentDoctorName : '' }}</div>
          <div class="row flex-item">护士：{{ hasPatient ? item.headNurseName : '' }}</div>
          <div class="row flex-item">住院：{{ hasPatient ? item.admissionDays : '' }}</div>
        </div>
      </div>
      <!-- 底部信息：住院号与状态标记 -->
      <div class="bedcard__footer">
        <div class="left">
          <span class="inpatient-no">{{ inpatientNo }}</span>
        </div>
        <div class="tags">
          <StatusTag :statusTags="statusTags" @tag-click="onTagClick" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="BedCard">
import StatusTag from '@/components/StatusTag/index.vue'
import { computed } from 'vue'
import { ElMessageBox } from 'element-plus'
import { dischargeBed } from '@/api/nurseWork/beds.js'
const proxy = getCurrentInstance().proxy

const { sys_settlement_type } = proxy.useDict('sys_settlement_type')

const props = defineProps({
  item: { type: Object, required: true }
})

const emit = defineEmits(['assign', 'detail', 'changeBed', 'discharged'])

const patient = ref({})
watch(
  () => props.item,
  newVal => {
    patient.value = newVal
  },
  {
    deep: true,
    immediate: true
  }
)

// 菜单定义（vue3-menus）：左键触发菜单
const menus = computed(() => {
  if (hasPatient.value) {
    return [
      {
        label: '换床',
        click: () => emit('changeBed', patient.value)
      },
      {
        label: '退床',
        divided: true,
        click: async () => {
          try {
            await ElMessageBox.confirm(
              `是否确认 ${patient.value.bedNo} ${patient.value?.patientName} 退床？`,
              '确认退床',
              {
                type: 'warning',
                confirmButtonText: '确认',
                cancelButtonText: '取消'
              }
            )
            await dischargeBed({
              id: patient.value.admissionId,
              bedId: patient.value.bedId
            })
            emit('discharged', patient.value)
            proxy.$modal.notifySuccess('退床成功')
          } catch (e) {
            // 用户取消
          }
        }
      }
    ]
  }
  return [
    {
      label: '分配',
      click: () => emit('assign', patient.value)
    }
  ]
})

const hasPatient = computed(() => Boolean(patient.value.admissionId))
const renderKey = computed(() => {
  const status = hasPatient.value ? 'occupied' : 'empty'
  const aid = patient.value.admissionId ?? ''
  const bid = patient.value.bedId ?? props.item.bedId ?? props.item.id ?? ''
  return `${status}-${aid}-${bid}`
})
// 顶部展示字段
const genderClass = computed(() => (patient.value.gender === '1' ? 'icon-woman' : 'icon-man'))
const displayName = computed(() => (hasPatient.value ? patient.value.patientName : '空床'))

// 住院号：示例使用患者 id 或空字符串
const inpatientNo = computed(() =>
  hasPatient.value && patient.value.hospitalizationNumber ? String(patient.value.hospitalizationNumber) : ''
)

// 底部状态标记：示意用，真实项目应来自后端字段
const statusTags = computed(() => (hasPatient.value ? ['新', '在', 'Ⅰ', '危', '欠', '执', '核'] : []))

// 根据出生日期计算年龄 --岁--月--天
const age = computed(() => {
  if (patient.value.birthDate) {
    const birthDate = new Date(patient.value.birthDate)
    if (isNaN(birthDate)) return ''
    const today = new Date()
    let age = today.getFullYear() - birthDate.getFullYear()
    const month = today.getMonth() - birthDate.getMonth()
    const day = today.getDate() - birthDate.getDate()
    if (month < 0 || (month === 0 && day < 0)) {
      age--
    }
    return `${age}`
  }
  return ''
})

// 左键点击：有患者打开详情，无患者打开分配
const onPatientClick = () => {
  emit('detail', patient.value)
}
const onAssignClick = () => {
  emit('assign', patient.value)
}

// 标签点击：示例将点击的标签值弹出或用于业务操作
const onTagClick = tag => {
  // 此处仅演示，真实业务可根据标签跳转或过滤
  // proxy.$modal.notifySuccess(`点击状态标签：${tag}`)
}
</script>

<style lang="scss" scoped>
@use '@/assets/styles/variables.module.scss' as *;

.bedcard-dropdown {
  flex: 0 0 316px;
}

.bedcard {
  border: 1px solid $border-color;
  border-radius: $border-radius;
  padding: 12px;
  background: #fff;
  box-shadow: 0 2px 8px 0 $box-shadow-color;
  cursor: pointer;
  transition:
    transform 0.18s ease,
    box-shadow 0.18s ease;
  user-select: none;
  width: 100%;
  height: 100%;
  font-size: 15px;
  display: grid;
  grid-template-rows: auto 1fr auto;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px 0 $box-shadow-color;
  }

  &.is-empty {
    .name {
      color: #909399;
    }
  }
}

.bedcard__header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .left {
    display: flex;
    align-items: center;
    gap: 6px;
    .iconfont {
      color: $icon-color;
      font-size: 20px;
    }
    .name {
      font-weight: 700;
      font-size: 18px;
      color: $blue;
    }
    .age {
      color: #606266;
    }
  }
  .right {
    .bedno {
      color: #606266;
      font-weight: 700;
    }
  }
}

.bedcard__body {
  margin-top: 8px;
  line-height: 18px;

  .row {
    margin: 4px 0;
    word-break: break-word;
  }
  .flex {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 4px;
  }
  .flex-item {
    flex: 1;
  }
}

.bedcard__footer {
  margin-top: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  min-height: 32px;
  border-top: 1px solid $border-color;
  margin-top: 8px;
  .inpatient-no {
    color: #606266;
    font-weight: 500;
  }
  .tags {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
    .tag {
      padding: 2px 6px;
      border: 1px solid $border-color;
      border-radius: 4px;
      font-size: 12px;
      color: #606266;
      background: #fafafa;
      &.error {
        background: $red;
        color: #fff;
      }
      &.warning {
        background: $yellow;
        color: #fff;
      }
      &.success {
        background: $green;
        color: #fff;
      }
      &.info {
        background: $blue;
        color: #fff;
      }
    }
  }
}
</style>
